// pages/yuyue/index.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		...makeData(),
		currentDate: wx.$timeUtil.format('yyyy-MM-dd'),
    sysConfig: null,
    protocol: false
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.tryAllowShareMessage(options);
		wx.$model.home.sysConfig().then((res) => {
			this.setData({
				sysConfig: res
			})
		});
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
	},

	/**
	 * 提交订单
	 */
	placeSubmit: function(e) {
    if (!this.data.protocol) {
      wx.showToast({
        title: '请同意协议',
        icon: 'none'
      })
      return
    }

		const values = e.detail.value;
		values.name = values.name.trim();
		values.phone = values.phone.trim();
		values.age = parseInt(values.age);

		if (!values.name.length) {
			return wx.hintError("请填写姓名");
		}

		if (isNaN(values.age)) {
			return wx.hintError("请填写年龄");
		}

		if (values.age < 0 || values.age > 200) {
			return wx.hintError("年龄不合法[0-200]");
		}

		if (!values.phone.length) {
			return wx.hintError("请填写手机号");
		}

		values.goto_time = this.data.$date;
		if (!values.goto_time) {
			return wx.hintError("请选择到院时间");
		}

		values.store_id = wx.$getStoreId();

		wx.$trySyncUserInfo().then(function() {
			return wx.$model.user.placeOrder(values, {
				loading: true
			})
		}).then(() => {
			wx.showModal({
				content: '已提交预约！',
				showCancel: false,
				success: () => {
					this.setData(makeData());
				}
			});
		});
	},

	/**
	 * 跳转地址
	 */
	gotoLocation: function() {
		let location = this.data.sysConfig.hospital_location;
		location = location.split(',', 2).map(parseFloat);
		const address = this.data.sysConfig.hospital_addr;

		wx.openLocation({
			address: address,
			latitude: location[1],
			longitude: location[0]
		});
  },
  
  protocolChange () {
    this.setData({
      protocol: !this.data.protocol
    })
  },
  goProtocol (e) {
    const type = e.target.dataset.type

    wx.navigateTo({
      url: '/pages/protocol/protocol?type=' + type,
    })
  }
});

function makeData() {
	return {
		name: '',
		age: '',
		$date: ''
	};
}
